package com.delayqueue.master.netty.handler.registry;

import com.delayqueue.common.enums.MessageType;
import com.delayqueue.common.netty.Address;
import com.delayqueue.common.netty.NettyMessage;
import com.delayqueue.common.netty.NettyUtil;
import com.delayqueue.common.netty.Node;
import com.delayqueue.master.cache.ConnectCacheFactory;
import com.delayqueue.master.config.NettyConfig;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ChannelHandler.Sharable
public class RegistryConnectHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private RegistryConnectBootstrap registryConnectBootstrap;

    @Autowired
    private NettyConfig nettyConfig;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Address address = NettyUtil.getRemoteAddress(ctx);
        Node node = new Node(address);
        node.setChannelHandlerContext(ctx);
        ConnectCacheFactory.registry.change(node);
        ConnectCacheFactory.registry.sendMessage(new NettyMessage(MessageType.MASTER_ONLINE, nettyConfig.getPort() + ""));
        log.info("连接注册中心成功！");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("已断开注册中心连接，正在重连");
        registryConnectBootstrap.connect();
    }
}
